package com.tmsps.ne4weixin.api;

import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tmsps.ne4weixin.bean.BaseResultBean;
import com.tmsps.ne4weixin.bean.tag.Tag;
import com.tmsps.ne4weixin.bean.tag.UserTag;
import com.tmsps.ne4weixin.config.WxConfig;
import com.tmsps.ne4weixin.utils.WXHttpUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @Title: TagAPI.java
 * @Package: com.tmsps.ne4weixin.api
 * @Description: 标签管理API
 * @author: hanjiefei
 * @date: 2019-10-22
 * @version V1.0
 * @Copyright: 2019 
 */
@Slf4j
public class TagAPI extends BaseAPI {
	
	private String accessToken = null;
	
	public TagAPI(String accessToken) {
		super(null);
		this.accessToken = accessToken;
	}
	
	public TagAPI(WxConfig config) {
		super(config);
		this.accessToken = config.getAccessToken();
	}

	/**
	 * 创建标签
	 * @param name	标签名
	 * @return
	 */
	public UserTag addTag(String name) {
		String url = String.format(ADD_TAGS, accessToken);
		UserTag userTag = new UserTag(new Tag(name));
		log.info("创建标签{}",JSONObject.toJSONString(userTag));
		String result = WXHttpUtil.postJson(url, JSONObject.toJSONString(userTag));
		log.info("创建标签返回结果{}",result);
		return JSONObject.parseObject(result, UserTag.class);
	}
	
	/**
	 * 编辑标签
	 * @param id	标签id
	 * @param name	标签名
	 * @return
	 */
	public BaseResultBean editTag(Integer id, String name) {
		String url = String.format(UPDATE_TAGS, accessToken);
		UserTag userTag = new UserTag(new Tag(id, name));
		log.info("编辑标签{}",JSONObject.toJSONString(userTag));
		String result = WXHttpUtil.postJson(url, JSONObject.toJSONString(userTag));
		log.info("编辑标签返回结果{}",result);
		return JSONObject.parseObject(result,BaseResultBean.class);
	}
	
	/**
	 * 获取公众号已创建的标签
	 * @return
	 */
	public List<Tag> getTags() {
		String url = String.format(GET_TAGS, accessToken);
		String result = WXHttpUtil.get(url);
		log.info("获取标签返回信息：{}",result);
		JSONObject obj = JSON.parseObject(result);
		return JSON.parseArray(obj.getString("tags"), Tag.class);
	}
	
	/**
	 * 删除标签
	 * @param id	标签id
	 * @return
	 */
	public BaseResultBean deleteTag(Integer id) {
		String url = String.format(DEL_TAGS, accessToken);
		UserTag userTag = new UserTag(new Tag(id));
		log.info("删除标签{}",JSONObject.toJSONString(userTag));
		String result = WXHttpUtil.postJson(url, JSONObject.toJSONString(userTag));
		log.info("删除标签返回结果{}",result);
		return JSONObject.parseObject(result,BaseResultBean.class);
	}
	
}
